package com.ruoyi.peach.service.impl;

import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.List;

import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.ruoyi.peach.mapper.RecordImgMapper;
import com.ruoyi.peach.domain.RecordImg;
import com.ruoyi.peach.service.IRecordImgService;

/**
 * 采集记录图片Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-10-09
 */
@Service
public class RecordImgServiceImpl implements IRecordImgService 
{
    @Autowired
    private RecordImgMapper recordImgMapper;

    // 从配置文件中获取上传文件的基础路径
    @Value("${ruoyi.profile:}")
    private String uploadBasePath;

    /**
     * 查询采集记录图片
     * 
     * @param id 采集记录图片主键
     * @return 采集记录图片
     */
    @Override
    public RecordImg selectRecordImgById(Long id)
    {
        return recordImgMapper.selectRecordImgById(id);
    }

    public List<RecordImg> selectRecordImgByrecordId(Long recordId)
    {
        return recordImgMapper.selectRecordImgByrecordId(recordId);
    }

    /**
     * 查询采集记录图片列表
     * 
     * @param recordImg 采集记录图片
     * @return 采集记录图片
     */
    @Override
    public List<RecordImg> selectRecordImgList(RecordImg recordImg)
    {
        return recordImgMapper.selectRecordImgList(recordImg);
    }

    /**
     * 新增采集记录图片
     * 
     * @param recordImg 采集记录图片
     * @return 结果
     */
    @Override
    public int insertRecordImg(RecordImg recordImg)
    {
        return recordImgMapper.insertRecordImg(recordImg);
    }

    /**
     * 修改采集记录图片
     * 
     * @param recordImg 采集记录图片
     * @return 结果
     */
    @Override
    public int updateRecordImg(RecordImg recordImg)
    {
        return recordImgMapper.updateRecordImg(recordImg);
    }

    /**
     * 批量删除采集记录图片
     * 
     * @param ids 需要删除的采集记录图片主键
     * @return 结果
     */
    @Override
    public int deleteRecordImgByIds(Long[] ids)
    {
        return recordImgMapper.deleteRecordImgByIds(ids);
    }

    /**
     * 删除采集记录图片信息
     * 
     * @param id 采集记录图片主键
     * @return 结果
     */
    @Override
    public int deleteRecordImgById(Long id)
    {
        return recordImgMapper.deleteRecordImgById(id);
    }

    @Override
    public int uploadImg(RecordImg recordImg) {
        Long recordId = recordImg.getRecordId();
        Date uploadTime = recordImg.getUploadTime();
        String newImgUrls = recordImg.getImgUrls();

        // 查询是否已存在相同 record_id + upload_time 的记录
        RecordImg existing = recordImgMapper.selectByRecordIdAndUploadTime(recordId, uploadTime);

        if (existing != null) {
            // 存在则拼接图片地址
            String oldUrls = existing.getImgUrls();
            String mergedUrls;

            if (oldUrls == null || oldUrls.trim().isEmpty()) {
                mergedUrls = newImgUrls;
            } else {
                mergedUrls = oldUrls + "," + newImgUrls;
            }

            existing.setImgUrls(mergedUrls);

            return recordImgMapper.updateRecordImg(existing);
        } else {
            // 不存在则插入新记录

            return recordImgMapper.insertRecordImg(recordImg);
        }
    }

    /**
     * 根据图片URL下载图片
     */
    @Override
    public byte[] downloadImage(String imgUrl) throws IOException {
        if (!StringUtils.hasText(imgUrl)) {
            return null;
        }

        Path imagePath;

        // 处理路径逻辑，结合配置的基础路径
        if (imgUrl.startsWith("/") || imgUrl.contains(":\\") || imgUrl.startsWith("file://")) {
            // 绝对路径
            imagePath = Paths.get(imgUrl.replace("file://", ""));
        } else {
            // 相对路径，拼接上传基础路径
            if (!StringUtils.hasText(uploadBasePath)) {
                throw new IOException("上传文件基础路径未配置(ruoyi.profile)");
            }
            // 从配置中获取的基础路径 + 相对路径
            imagePath = Paths.get(uploadBasePath).resolve(imgUrl).normalize();
        }

        // 检查文件是否存在
        if (!Files.exists(imagePath)) {
            throw new IOException("图片文件不存在: " + imagePath);
        }

        // 检查是否是文件
        if (!Files.isRegularFile(imagePath)) {
            throw new IOException("路径不是有效的文件: " + imagePath);
        }

        return Files.readAllBytes(imagePath);
    }

}
